package com.dcy.common.base.interceptor;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ClassLoaderUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.handler.DataPermissionHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import com.dcy.common.annotation.DataScopeColumn;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

/**
 * @author dcy
 * @description 数据权限拦截器
 * @createTime 2023/1/2 10:51
 */
public class DcyDataPermissionInterceptor extends DataPermissionInterceptor {

    @Override
    public void setDataPermissionHandler(DataPermissionHandler dataPermissionHandler) {
        super.setDataPermissionHandler(dataPermissionHandler);
    }

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
        if (ms.getSqlCommandType() == SqlCommandType.SELECT) {
            //获取mapper名称
            String className = StrUtil.subBefore(ms.getId(), StringPool.DOT, true);
            //获取方法名
            String methodName = StrUtil.subAfter(ms.getId(), StringPool.DOT, true);
            DataScopeColumn dataScopeColumn = AnnotationUtil.getAnnotation(ReflectUtil.getMethodByName(ClassLoaderUtil.loadClass(className), methodName), DataScopeColumn.class);
            if (dataScopeColumn != null) {
                PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);
                mpBs.sql(parserSingle(mpBs.sql(), ms.getId()));
            }
        }
    }

}
